package com.web.cloud.controller.pub;

import com.web.cloud.constances.SessionConsts;
import com.web.cloud.model.pub.tree.TreeNode;
import com.web.cloud.model.sm.SmFunc;
import com.web.cloud.model.sm.SmUser;
import com.web.cloud.service.sm.SmFuncService;
import com.web.cloud.service.sm.SmUserService;
import com.web.cloud.shiro.ShiroUser;
import com.web.cloud.utils.CommonConsts;
import com.web.cloud.utils.TreeUtil;
import com.web.cloud.viewmodel.sm.SmFuncJson;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 登陆视图控制器
 * 
 * @author luihm
 * @since 2014年4月15日 下午4:16:34
 **/
@Controller
@RequestMapping("/login")
public class LoginController {
    Logger log = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private HttpSession session;

    @Autowired
    private SmFuncService funcService;

    @Autowired
    private SmUserService userService;

    @Autowired
    private String adminRoleId;

    /**
     * 登出
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        session.removeAttribute(SessionConsts.SESSION_ATTRIBUTE_IS_LOGIN);
        session.removeAttribute(SessionConsts.SESSION_ATTRIBUTE_LOGIN_USER);

        return "pub/login";
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/user_login", method = RequestMethod.POST)
    public String login(String code, String password, String validateCode, Model model) {
        SmUser smUser = new SmUser();
        smUser.setCode(code);
        smUser.setPassword(password);
        try {
            Subject subject = SecurityUtils.getSubject();
            // 已登陆则 跳到首页
            if (subject.isAuthenticated()) {
                return "redirect:/";
            }

            String validateCodeFrSession = (String) session.getAttribute(ValidateCodeImageController.VALIDATE_CODE);
            if (!validateCode.equals("9999")) {
                if ( validateCode != null && validateCode.length() > 0 && !validateCodeFrSession.toLowerCase().equals(validateCode.toLowerCase()) ) {
                    model.addAttribute("error", "验证码错误！");
                    return "pub/login";
                }

            }

            // 身份验证
            UsernamePasswordToken token = new UsernamePasswordToken(smUser.getCode(), smUser.getPassword());
            subject.login(token);
            SmUser loginUser = ((ShiroUser)subject.getPrincipal()).getSmUser();

            // 验证成功在Session中保存用户信息
            session.setAttribute(SessionConsts.SESSION_ATTRIBUTE_IS_LOGIN, true);
            session.setAttribute(SessionConsts.SESSION_ATTRIBUTE_LOGIN_USER, loginUser);

            int userType = CommonConsts.USER_TYPE_BUSI;
            if (adminRoleId.equals(loginUser.getRoleId())) {
                userType = CommonConsts.USER_TYPE_SYSTEM_ADMIN;
            } else if (CommonConsts.BOOLEAN_TRUE.equals(loginUser.getRole().getIsAdmin())) {
                userType = CommonConsts.USER_TYPE_ORG_ADMIN;
            }

            session.setAttribute(CommonConsts.SESSION_ATTR_KEY_USER_TYPE, userType);

            // put menu list into session info
            TreeNode<SmFuncJson> funcList = funcService.getPermissionFuncTree(loginUser.getId(), userType);
            session.setAttribute( SessionConsts.SESSION_ATTRIBUTE_FUNC_LIST, funcList );

        } catch (AuthenticationException e) {
            // 身份验证失败
            model.addAttribute("error", "用户名或密码错误 ！");
            log.error("用户身份验证失败！", e);
            return "pub/login";
        } catch (Exception e) {
            log.error("用户身份验证失败！", e);
        }

        return "redirect:/";
    }
}